package com.nonsense.textsummary

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.rounded.ArrowDropDown
import androidx.compose.material.icons.rounded.Check
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.PlayArrow
import androidx.compose.material.icons.rounded.Warning
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response


const val TAG = "TextSummary"

@Preview
@OptIn(ExperimentalMaterial3Api::class, DelicateCoroutinesApi::class)
@Composable
fun TextSummary() {
    var ip by remember { mutableStateOf("192.168.0.106") }
    var port by remember { mutableStateOf("5000") }

    var text by remember { mutableStateOf("今日，中国三条重要高铁干线——兰新高铁、贵广铁路和南广铁路将开通运营。其中兰新高铁是中国首条高原高铁，全长1776公里，最高票价658元。贵广铁路最贵车票320元，南广铁路最贵车票206.5元，这两条线路大大缩短西南与各地的时空距离。出行更方便了！中国“高铁版图”再扩容 三条重要高铁今日开通") }
    var result by remember { mutableStateOf("") }
    var state by remember { mutableStateOf(LoadingState.idle) }


    Column(
        modifier = Modifier.verticalScroll(
            state = rememberScrollState()
        )
    ) {
        Row(
            modifier = Modifier
                .padding(20.dp)
                .fillMaxWidth(),
        ) {
            OutlinedTextField(
                value = ip,
                onValueChange = {
                    ip = it
                    state = LoadingState.idle
                },
                label = {
                    Row() {
                        Text("ip")
                        if (ipCheck(ip)) {
                            Icon(
                                Icons.Rounded.Check,
                                contentDescription = "Correct",
                                tint = Color.Green,
                                modifier = Modifier
                                    .size(20.dp)
                                    .align(alignment = Alignment.CenterVertically)
                            )
                        } else {
                            Icon(
                                Icons.Rounded.Close,
                                contentDescription = "Error",
                                tint = Color.Red,
                                modifier = Modifier
                                    .size(20.dp)
                                    .align(alignment = Alignment.CenterVertically)
                            )
                        }
                    }
                },
                maxLines = 1,
                modifier = Modifier.weight(12f)
            )

            Box(modifier = Modifier.weight(1f))
            OutlinedTextField(
                value = port,
                onValueChange = {
                    port = it
                    state = LoadingState.idle
                },
                label = {
                    Row() {
                        Text("port")
                        if (portCheck(port)) {
                            Icon(
                                Icons.Rounded.Check,
                                contentDescription = "Correct",
                                tint = Color.Green,
                                modifier = Modifier
                                    .size(20.dp)
                                    .align(alignment = Alignment.CenterVertically)
                            )
                        } else {
                            Icon(
                                Icons.Rounded.Close,
                                contentDescription = "Error",
                                tint = Color.Red,
                                modifier = Modifier
                                    .size(20.dp)
                                    .align(alignment = Alignment.CenterVertically)
                            )
                        }
                    }
                },
                modifier = Modifier.weight(6f),
                maxLines = 1,
            )
        }
        OutlinedTextField(
            value = text,
            onValueChange = {
                text = it
                result = ""
                state = LoadingState.idle
            },
            label = { Text("请输入新闻") },
            modifier = Modifier
                .padding(20.dp)
                .fillMaxWidth()
                .height(300.dp),
            maxLines = 10,
        )
        OutlinedButton(onClick = {
            when (state) {
                in setOf<LoadingState>(
                    LoadingState.idle,
                    LoadingState.failure
                ) -> {
                    state = LoadingState.isLoading
                    try {
                        if (ipCheck(ip) or portCheck(port)) {
                            Network.update(ip, port)
                        }
                        Network.service.summary(text).enqueue(object :
                            Callback<String> {

                            override fun onResponse(
                                call: Call<String>,
                                response: Response<String>
                            ) {
                                response.body()?.let {
                                    result = it
                                    state = LoadingState.success
                                }
                            }

                            override fun onFailure(call: Call<String>, t: Throwable) {
                                Log.d(TAG, "request wrong!")
                                t.printStackTrace()
                                // 使用TextRank本地运算
                                GlobalScope.launch {
                                    withContext(Dispatchers.IO) {
                                        TextRankSummary.getTopSentenceList(text, 1)[0]
                                    }?.let {
                                        result = it
                                        state = LoadingState.success
                                    }
                                }
                            }
                        })
                    } catch (e: Exception) {
                        Log.d(TAG, "生成摘要失败")
                        e.printStackTrace()
                        state = LoadingState.failure
                        result = "生成摘要失败, 请重试!"
                    }
                }

                else -> {}
            }

        }, modifier = Modifier.align(alignment = Alignment.CenterHorizontally)) {
            when (state) {
                LoadingState.idle -> {
                    Text("生成摘要")
                }

                LoadingState.isLoading -> {
                    DefaultLoading()
                }

                LoadingState.success -> {
                    Text("生成成功")
                }

                LoadingState.failure -> {
                    Text("重新生成")
                }
            }

        }
        OutlinedTextField(
            value = result,
            onValueChange = { },
            label = { Text("摘要") },
            modifier = Modifier
                .padding(20.dp)
                .fillMaxWidth()
                .height(210.dp),
            maxLines = 7,
            readOnly = true,
        )
    }
}
